
const puppeteer = require('puppeteer')
const chalk = require('chalk')
const CosmeticsDetail = require('../controllers/base/cosmeticsDetail')
const log = console.log

let arg = process.argv.splice(2)
const key = arg[0]
const total = arg[1]

start(key, total)


module.exports = function(key, total) {
  start(key, total)
}

function formatProgress (current, total) { 
  let percent = (current / total) * 100
  let done = ~~(current / total * 40)
  let left = 40 - done
  let str = `progress: [${''.padStart(done, '=')}${''.padStart(left, '-')}]  ${percent}%`
  return str
}

async function start(key, total) {
  const browser = await puppeteer.launch({
    handless: false,
    // devtools: true
    // args: ['--start-maximized']
  })
  log(chalk.green('server start...'))
  try {
    const page = await browser.newPage()
    page.on('console', msg => {
      if (typeof msg === 'object') {
        console.dir(msg)
      } else {
        log(chalk.blue(msg))
      }
    })

    await page.goto(`https://search.jd.com/Search?keyword=${key}&qrst=1&stock=1&page=1&s=1&click=0`)
    log(chalk.yellow('first loading...'))

    for (let i = 1; i <= total; i++) {
      const submit = await page.$('.pn-next')
      await submit.click()

      await page.evaluate(() => {
        for (var y = 0; y <= 5000; y += 500) {
          window.scrollTo(0,y)
          }
      })
      await page.waitFor(6000)

      console.clear()
      log(chalk.yellow(formatProgress(i, total)))
      log(chalk.yellow('page loaded.'))

      let r = await handleData()

      log(chalk.yellow('insert database...'))
      await page.waitFor(1000)
      await CosmeticsDetail.addCosmeticsDetail(key, r)
      console.clear()
      await page.waitFor(1000)

      log(chalk.yellow(formatProgress(i, total)))
      await page.waitFor(2000)
    }

    await browser.close()
    log(chalk.green('complete!'))

    async function handleData() {
      const list = await page.evaluate(() => {
        
        const writeDataList = []

        let itemList = document.querySelectorAll('.gl-item')

        for (let item of itemList) {
          let writeData = {
            picture: undefined,
            link: undefined,
            title: undefined,
            price: undefined
          }

          let imgItem = item.querySelector('.p-img')

          let img = imgItem.getElementsByTagName('img')[0].src || 'https:' + imgItem.getElementsByTagName('img')[0].dataset.lazyImg
          let a = imgItem.getElementsByTagName('a')
          let link = a[0].href
          writeData.picture = img

          writeData.link = link

          let price = item.querySelector('.p-price')
          writeData.price = price.innerText
          
          let title = item.querySelector('.p-name')
  
          writeData.title = title.innerText

          writeDataList.push(writeData)
        }
        return writeDataList
        
      })
      
      return list
    }

  } catch (error) {
    console.log(error)
    log(chalk.red('error'))
    await browser.close()
  } finally {
    process.exit(0)
  }
}
